<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 警告 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeName-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab -->
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="80px" label-position="top">
        <el-tabs tab-position="left" v-model="activeName" :before-leave="beforeTabLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader v-model="addForm.goods_cat" :options="cateList"
                :props="{ expandTrigger: 'hover', label:'cat_name',value: 'cat_id',}" @change="cateHandleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 动态 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="item1" border v-for="(item1 ,index) in item.attr_vals1" :key="index">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 静态 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :headers="headerObj" class="upload-demo" :action="picAction" :on-preview="picPreview"
              :on-remove="picRemove" :on-success="picSucess" :file-list="fileList" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 上传图片 -->
    <el-dialog title="图片预览" :visible.sync="picDialogVisible" width="50%">
      <img :src="imgUrl" alt="" width="100%">
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    var validatePass = (rule, value, callback) => {
      if (typeof (value) === 'number' && value > 0) {
        callback()
      } else {
        callback(new Error('必须是大于0的整数或小数'))
      }
    }
    return {
      // 激活的tab
      activeName: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: '',
        pics: [],
        goods_introduce: ''

      },
      // 级联分类
      cateList: [],
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 动态
      manyList: [],
      // 静态
      onlyList: [],
      // 上传图片URL
      picAction: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片
      fileList: [],
      // 上传图片请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览对话框显隐
      picDialogVisible: false,
      imgUrl: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类失败')
      this.cateList = res.data
      // console.log(res.data)
    },
    // 级联改变
    cateHandleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        return this.$message.warning('只允许为三级分类添加商品信息!')
      }
      // this.$message.success('选择商品分类成功')
      this.getSelList()
    },
    beforeTabLeave (to, from) {
      if (from === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // 动态静态参数
    async getSelList () {
      const id = this.addForm.goods_cat[2]
      const { data: res } = await this.$http.get(`categories/${id}/attributes`, { params: { sel: 'many' } })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      // console.log(res)
      res.data.forEach(item => {
        item.attr_vals1 = item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
      })
      this.manyList = res.data
      // console.log(this.manyList)
      const { data: res1 } = await this.$http.get(`categories/${id}/attributes`, { params: { sel: 'only' } })
      if (res1.meta.status !== 200) return this.$message.error('获取参数失败')
      this.onlyList = res1.data
      console.log(this.onlyList)
    },
    // 预览
    picPreview ({ response: { data } }) {
      console.log(data)
      this.imgUrl = data.url
      this.picDialogVisible = true
    },
    // 关闭
    picRemove ({ response: { data } }) {
      const i = this.addForm.pics.findIndex(item => item.pic === data.tmp_path)
      this.addForm.pics.splice(i, 1)
    },
    // 上传成功
    picSucess (response) {
      if (response.meta.status !== 200) return this.$message.error('添加图片失败')
      this.$message.success('添加图片成功')
      this.addForm.pics.push({
        pic: response.data.tmp_path
      })
      console.log(this.addForm.pics)
    },
    // 添加商品
    addGoods () {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return this.$message.error('亲,请填写必要的商品信息呦')
        const form = cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        form.attrs = []
        this.manyList.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          })
        })
        this.onlyList.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        // console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  }

}
</script>

<style scoped lang='less'>
.el-steps {
  margin: 20px 0;
}
.quill-editor {
  margin-bottom: 20px;
}
/deep/ .ql-editor {
  height: 240px;
}
</style>
